console.log('腾讯新闻插件脚本注入');
console.log(localStorage.getItem('chrome_test'))
// ============> utils
// 提取文章类型新闻页的信息
function extractNewDetail(){
  const article = document.querySelector('#article-content');
  const articleContainer = article.querySelector('.rich_media_content');
  const contents = {
    text: '',
    image: [],
    video: []
  }
  if (articleContainer){
    // const texts = Array.from(articleContainer.querySelectorAll('p, section'));
    const texts = Array.from(articleContainer.querySelectorAll('.rich_media_content > p, .rich_media_content > section'));
    // console.log(texts)
    const newTexts = texts.reduce((texts, currentP) => {
      if (currentP.tagName === 'P' && !currentP.className.includes('qqnews_image_desc') && currentP.textContent.trim()){
        texts += currentP.textContent.trim() + '\n';
      }
      if (currentP.tagName === 'SECTION' && Object.keys(currentP.dataset).length < 1 && currentP.textContent.trim()){
        texts += currentP.textContent.trim() + '\n';
      }
      return texts;
    }, '');
    console.log('新闻文本内容如下：');
    console.log(newTexts)
    contents.text = newTexts.trim();
    const imgs = articleContainer.querySelectorAll('img.qnt-img-img.qnr-img-lazy-load-img');
    if (imgs.length > 0){
      imgs.forEach(img => {
        contents.image.push(img.currentSrc);
      })
      console.log('图片信息： ');
      console.log(contents.image)
    }
    // 包含视频处理
    // const videoContainer = articleContainer.querySelector('.videoPlayer');
    // const videos = Array.from(videoContainer.getElementsByTagName('video'));
    // if (videos.length > 0){
    //   videos.forEach(video => {
    //     if (video.src){
    //       let xhr = new XMLHttpRequest();
    //       xhr.open('get', video.src, true);
    //       xhr.responseType = 'blob';
    //       xhr.onload = function (){
    //         console.log(this)
    //       }
    //       xhr.send();
    //     }
    //   })
    // }
    const videos = Array.from(articleContainer.querySelectorAll('._mod_thumbplayer_container_'));
    if (videos.length > 0) {
      videos.forEach(vDom => {
        if (vDom.id && vDom.id.indexOf('-') > 0){
          let videoDetail = localStorage.getItem(`ce-${vDom.id.slice(0, vDom.id.indexOf('-'))}`);
          if (videoDetail) {
            videoDetail = JSON.parse(videoDetail);
            contents.video.push({
              title: videoDetail.title,
              urls: videoDetail.urls
            });
          }
        }
      });
    }
    return contents;
  } else {
    return false;
  }
}

// 提取视频类型新闻页的信息
function extractVideoDetail(){
  let videoDoms = document.getElementsByClassName('_mod_thumbplayer_container_');
  if (videoDoms.length > 0){
    let content = { video: [] };
    let videoDivs = Array.from(videoDoms);
    let videoIds = videoDivs.map(divDom => {
      if (divDom.id && divDom.id.lastIndexOf('-') > 0){
        return divDom.id.slice(divDom.id.lastIndexOf('-') + 1);
      }
    });
    videoIds.forEach(idKey => {
      let videoDetail = localStorage.getItem(`ce-${idKey}`);
      if (videoDetail){
        videoDetail = JSON.parse(videoDetail);
        content.video.push({
          title: videoDetail.title,
          urls: videoDetail.urls
        });
      }
    });
    return content;
  } else {
    return false;
  }
}
// 处理新闻请求
function handleNew(){
  // 文章
  // /rain/a/20250306A0AOSN00
  // 视频
  // /rain/a/20250305V0ADYL00
  // 专题
  // /rain/a/UTR2025022800675800
  let subjectReg = /\/rain\/a\/\w{8}A/i;
  let videoReg = /\/rain\/a\/\w{8}V/i;
  if (subjectReg.test(window.location.pathname)){
    // 当前新闻页符合提取
    return extractNewDetail();
  } else if (videoReg.test(window.location.pathname)) {
    return extractVideoDetail();
  } else {
    // 当前新闻页不符合提取新闻元素标准
    return false;
  }
}

// 消息监听
chrome.runtime.onMessage.addListener((message, sender, sendMessage) => {
  console.log(message)
  // 后台发送的采集新闻页信息消息
  if (message.id === 'newDetail'){
    const result = handleNew();
    sendMessage(result);
  }
});